﻿using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace Gaea.Oracle
{
    public class GaeaOracleAdapter : GaeaAdapter
    {
        public override string AppendColumnNameEqualsValue(string columnName)
        {
            return $"{columnName}=:{columnName}";
        }
        public override string FindByIdCommandText(out string paramName, string name, string key)
        {
            paramName = ":id";
            return $"SELECT * FROM {name} WHERE {key}={paramName}";
        }


        public override string InsertCommandText(string name, List<PropertyInfo> columnProperties)
        {
            var stringBuilderColumn = new StringBuilder();
            var stringBuilderProperty = new StringBuilder();

            for (var i = 0; i < columnProperties.Count; i++)
            {
                var property = columnProperties[i];

                stringBuilderColumn.Append(property.Name);
                stringBuilderProperty.AppendFormat(":{0}", property.Name);

                AppendColumnNameEqualsValue(property.Name);
                if (i < columnProperties.Count - 1)
                {
                    stringBuilderColumn.Append(", ");
                    stringBuilderProperty.Append(", ");
                }

            }
            return $"BEGIN INSERT INTO {name} ({stringBuilderColumn.ToString()}) VALUES({stringBuilderProperty.ToString()}) RETURNING id INTO :return_id;END;";

        }

        public override int Insert(IDbConnection connection, IDbTransaction transaction, string commandText, object entityToInsert, int? commandTimeout)
        {

            var parameters = new DynamicParameters(entityToInsert);
            parameters.Add(":return_id", ParameterDirection.Output);

            connection.Execute(commandText, parameters, transaction, commandTimeout);
            return parameters.Get<int>(":return_id");
        }

        public override async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, string commandText, object entityToInsert, int? commandTimeout)
        {
            var parameters = new DynamicParameters(entityToInsert);
            parameters.Add(":return_id", ParameterDirection.Output);

            await connection.ExecuteAsync(commandText, parameters, transaction, commandTimeout);
            return parameters.Get<int>(":return_id");
        }
    }
}
